package jjn.offer_round2;

import java.util.Arrays;

/**
 * @author Jiang Jining
 * @since 2023-06-21 23:50
 */
public class Offer29 {
    public int[] spiralOrder(int[][] matrix) {
        int left = 0, right = matrix[0].length - 1;
        int top = 0, bottom = matrix.length - 1;
        int[] result = new int[matrix.length * matrix[0].length];
        int index = 0;
        while (true) {
            for (int i = left; i <= right; i++) {
                result[index] = matrix[top][i];
                index++;
            }
            top++;
            if (top > bottom) {
                break;
            }
            for (int i = top; i <= bottom; i++) {
                result[index] = matrix[i][right];
                index++;
            }
            right--;
            if (right < left) {
                break;
            }
            for (int i = right; i >= left; i--) {
                result[index] = matrix[bottom][i];
                index++;
            }
            bottom--;
            if (bottom < top) {
                break;
            }
            for (int i = bottom; i >= top; i--) {
                result[index] = matrix[i][left];
                index++;
            }
            left++;
            if (left > right) {
                break;
            }
        }
        return result;
    }
    
    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        int[] spiralOrder = new Offer29().spiralOrder(matrix);
        System.out.println("spiralOrder = " + Arrays.toString(spiralOrder));
    }
}
